package test05.demo1;

public class MyRunnable implements Runnable {
    private static Object lock = new Object(); // 共享锁，保证所有线程同步

    private String way;
    private int count;

    private static int sum = 5000; // 共享余额，保证多个线程操作的是同一个账户

    public MyRunnable(String way, int count) {
        this.way = way;
        this.count = count;
    }

    @Override
    public void run() {
            String name = Thread.currentThread().getName();
            synchronized (lock) { // 线程同步
                if (sum >= count) {
                    try {
                        Thread.sleep(100); // 模拟取钱的延迟
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    sum -= count;
                    System.out.printf("%s 用 %s 取钱成功，取出 %d 元，剩余余额：%d 元%n", name, way, count, sum);
                    return; // 取钱成功，线程退出
                }
                    System.out.printf("%s 用 %s 取钱失败，余额不足！剩余余额：%d 元%n", name, way, sum);
            }
    }
}
